#include "tcpclient.h"
#include "lwip/netif.h"
#include "lwip/ip.h"
#include "lwip/tcp.h"
#include "lwip/init.h"
#include "netif/etharp.h"
#include "lwip/udp.h"
#include "lwip/pbuf.h"
#include <stdio.h>
#include <string.h>


static struct tcp_pcb* client_pcb = NULL;

static void client_err(void* arg, err_t err)
{
    printf("connect error! closed by core!!\n");
    printf("try to connect to server again!!\n");


    tcp_close(client_pcb);


    TCP_Client_Init();
}


static err_t client_send(void* arg, struct tcp_pcb* tpcb)
{
    uint8_t send_buf[] = "This is a TCP Client test...\n";


    tcp_write(tpcb, send_buf, sizeof(send_buf), 1);

    return ERR_OK;
}

static err_t client_recv(void* arg, struct tcp_pcb* tpcb, struct pbuf* p, err_t err)
{
    if (p != NULL) {

        tcp_recved(tpcb, p->tot_len);


        tcp_write(tpcb, p->payload, p->tot_len, 1);

        memset(p->payload, 0, p->tot_len);
        pbuf_free(p);
    }
    else if (err == ERR_OK) {

        printf("server has been disconnected!\n");
        tcp_close(tpcb);


        TCP_Client_Init();
    }
    return ERR_OK;
}

static err_t client_connected(void* arg, struct tcp_pcb* pcb, err_t err)
{
//  printf("connected ok!\n");


    tcp_poll(pcb, client_send, 2);


    tcp_recv(pcb, client_recv);

    return ERR_OK;
}

/* USER CODE BEGIN 0 */
#define DEST_IP_ADDR0               192
#define DEST_IP_ADDR1               168
#define DEST_IP_ADDR2               105
#define DEST_IP_ADDR3               150

#define DEST_PORT                  5001
void TCP_Client_Init(void)
{
    ip4_addr_t server_ip;

    client_pcb = tcp_new();

    IP4_ADDR(&server_ip, DEST_IP_ADDR0, DEST_IP_ADDR1, DEST_IP_ADDR2, DEST_IP_ADDR3);

//  printf("client start connect!\n");


    tcp_connect(client_pcb, &server_ip, TCP_CLIENT_PORT, client_connected);


    tcp_err(client_pcb, client_err);
}









